<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                  |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                     |
// +------------------------------------------------------------------------+
// | Author: liuxuliang@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
/**
 * 车商验车
 */

namespace AuctionBack\Controller;

use AuctionCore\AntNest\Sms;
use AuctionCore\System\AuctionException;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\CarCheck;
use AuctionCore\CarResource\Car;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\Dispute\Dispute;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Account\Back\Employee;

class DealerCheckCarController extends BaseController
{
    const PAGE_NUM = 1; // 默认起始页
    const PAGE_SIZE = 10; // 每页偏移量

    private $dataStatus;

    public function __construct()
    {
        $this->dataStatus = CarCheck::$dataStatus;

        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
    }

    /**
     * 车商验车模块主页面
     */
    public function index()
    {
        $status = I("get.status/d", CarCheck::STATUS_PENDING);
        $params = array(
            'page' => I("get.p", self::PAGE_NUM),
            'size' => self::PAGE_SIZE,
            'search' => array(
                'status' => $status,
            )
        );
        $content = $this->getPendingList($params);
        $this->assign('params', $params);
        $this->assign('content', $content);
        $this->display();
    }

    /**
     * 数据列表
     */
    public function getList()
    {
        $status = I("get.status/d", CarCheck::STATUS_PENDING);
        $params = array(
            'page' => I("get.p", self::PAGE_NUM),
            'size' => self::PAGE_SIZE,
            'search' => array(
                'status' => $status,
                'location_area' => I('get.location_area', ''),
                'order_no' => I('get.order_no', ''),
            )
        );
        if($status != CarCheck::STATUS_PENDING){
            //检查权限
            $rules = "CheShangYanCheChaKanSuoYou";
            $e = new Employee($this->user_info['username']);
            $auth = $e->check_auth($rules);
            $params['search']['auth'] = $auth;
            $params['search']['emp_id'] = $this->emp_id;
        }
        if (!in_array($status, $this->dataStatus)) {
            $this->showError('参数错误，请联系管理员');
        }
        $this->getPendingList($params, 1);
    }

    /**
     * 错误输出
     * 页面片段
     * @param  string $errMsg [description]
     *
     */
    public function showError($errMsg = '')
    {
        $this->assign('errMsg', $errMsg);
    }


    /**
     * 验车数据列表
     */
    private function getPendingList($params, $isDisplay = 0)
    {
        if (!$this->is_hq && $this->bc_city) {
            $params['search']['location_area'] = array('in', array_flip($this->bc_city));
        }
        //获取list
        $aol = new CarCheck();
        $result = $aol->dealer_check_car_list($params['page'], $params['size'], $params['search']);
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $params['size'], "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $page = $Page->show(); // 分页显示输出
        //模板赋值
        $this->assign('page', $page); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->assign("params", $params);
        $this->assign("dataStatus", $this->dataStatus);
        if ($isDisplay == 1) {
            $this->display('pendingList');
        } else {
            return $this->fetch('pendingList');
        }
    }

    /**
     * 车商验车处理详情页
     */
    public function deal()
    {
        //------获取数据
        $order_id = I('get.id');
        $CarCheck = new CarCheck($order_id);
        $detail = $CarCheck->car_dealer_check_detail();

        $bestPrice = \AuctionCore\Other\Price::getBestPrice($order_id);

        $car_detail = \AuctionCore\CarResource\Car::getDetailWithChannel($detail['car_id']);
        $this->assign('car_detail', $car_detail);

        $show_from = \AuctionCore\Other\Channel::get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);

        $transfer_type = C('TRANSFER_LIMIT');
        $this->assign('transfer_type', $transfer_type);

        //获取提车人信息
        $take_car_men = \AuctionCore\CarDealer\Dealer::getTakeCarMan($detail['dealer_id']);
        $this->assign('detail', $detail);
        $this->assign('bestPrice', $bestPrice);
        $this->assign('dataStatus', $this->dataStatus);
        $this->assign('transferType', $this->transferType);
        $this->assign('take_men', $take_car_men);
        $this->display();
    }

    /**
     * 车商验车详情展示页
     */
    public function view()
    {
        //------获取数据
        $order_id = I('get.id');
        $carCheck = new CarCheck($order_id);
        $detail = $carCheck->car_dealer_check_detail();
        $car_detail = \AuctionCore\CarResource\Car::getDetailWithChannel($detail['car_id']);
        $this->assign('car_detail', $car_detail);
        $bestPrice = \AuctionCore\Other\Price::getBestPrice($order_id);
        $show_from = \AuctionCore\Other\Channel::get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $transfer_type = C('TRANSFER_LIMIT');
        $this->assign('transfer_type', $transfer_type);
        //获取提车人信息
        $take_car_men = \AuctionCore\CarDealer\Dealer::getTakeCarMan($detail['dealer_id']);
        $this->assign('detail', $detail);
        $this->assign('bestPrice', $bestPrice);
        $this->assign('dataStatus', $this->dataStatus);
        $this->assign('transferType', $this->transferType);
        $this->assign('take_men', $take_car_men);
        $this->display();
    }

    /**
     * 验证拍单编号是否有效
     * @param string $orderID
     * @return bool
     */
    private function checkConsultOrderByID($orderID = '')
    {
        // 判断ID格式是否正确
        if (empty($orderID) || !is_numeric($orderID)) {
            $this->helpJsonResult(400, '当前操作拍单编号异常!');
        }
        // 判断ID是否有效
        $o = new AuOrder($orderID);
        $orderInfo = $o->detail();
        if (!is_array($orderInfo) || empty($orderInfo['order_no'])) {
            $this->helpJsonResult(400, '当前操作拍单编号无效!');
        }
        if ($orderInfo['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        return true;
    }

    /**
     * 验车通知
     */
    public function checkNote()
    {
        if (!IS_POST) $this->helpJsonResult(500, "当前请求方式不合法！");
        $check_id = I('post.c_id'); // 车商验车ID
        $checkInfo = \AuctionCore\CarResource\CarCheck::detail_by_check_id($check_id);
        $order = new AuOrder($checkInfo['order_id']);
        $order_detail = $order->detail();
        if ($order_detail['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        if (empty($checkInfo)) {
            $this->helpJsonResult(500, '读取验车记录失败！');
        }
        $params = array();
        // 获取表单信息
        $params['check_id'] = $check_id; // 车商验车ID
        $params['car_id'] = $order_detail['car_id']; //车辆ID
        $params['order_id'] = $checkInfo['order_id']; // 车商验车ID
        $params['dealer_id'] = $checkInfo['dealer_id']; // 车商验车ID
        $params['emp_id'] = $this->emp_id;
        $params['status'] = $this->dataStatus['following']; // 处理结果(0:待处理, 1:跟踪中, 2:验车成功 3:验车失败)
        $params['dataStatus'] = $this->dataStatus;
        try {
            $CarCheck = new CarCheck();
            $res = $CarCheck->save_car_dealer_check($params);
        } catch (AuctionException $ex) {
            $this->helpJsonResult(500, $ex->getMessage());
        }
        if ($res !== false) {
            $this->helpJsonResult(200, '更新成功');
        } else {
            $this->helpJsonResult(500, '验车通知失败');
        }
    }

    /**
     * 验车通知短信发送
     */
    public function checkMsgSend()
    {
        if (!IS_POST) $this->helpJsonResult(500, "当前请求方式不合法！");
        //------获取数据
        $order_id = I('post.o_id');
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if ($order_detail['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        $CarCheck = new CarCheck($order_id);
        $detail = $CarCheck->car_dealer_check_detail();
        //短信发送
        $revAddress = \AuctionCore\CarOwner\Owner::get_reserve_address($detail['delive_store'], $detail['owner_id']);
        $params = array(
            'order_number' => $detail['order_no'],
            'check_limit_time' => date('Y年m月d日', strtotime($detail['check_limit_time'])),
            'check_addr' => $revAddress,
        );
        $phone = $detail['contact_mobile'];
        try {
            $sms = new Sms();
            $res = $sms->notify(20, $phone, $params);
        } catch (AuctionException $ex) {
            $this->helpJsonResult(500, $ex->getMessage());
        }
        if ($res !== false) {
            /**
             * 记录车辆跟踪日志
             */
            $car_action_data = array(
                'action_name' => "车商验车，发送短信",
                'emp_id' => $this->emp_id
            );
            \AuctionCore\CarResource\Car::add_car_trace_log($detail['car_id'], $car_action_data);
            /**
             * 记录拍品跟踪日志
             */
            $order_action_data = array(
                'action_name' => "车商验车，发送短信",
                'emp_id' => $this->emp_id
            );
            \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
            $this->helpJsonResult(200, '更新成功');
        } else {
            $this->helpJsonResult(500, '验车通知短信发送失败');
        }
    }

    /**
     * 违约
     */
    public function checkViolate()
    {
        if (!IS_POST) $this->helpJsonResult(500, "当前请求方式不合法！");
        $check_id = I('post.c_id'); // 车商验车ID
        $checkInfo = \AuctionCore\CarResource\CarCheck::detail_by_check_id($check_id);
        $order = new AuOrder($checkInfo['order_id']);
        $order_detail = $order->detail();
        if ($order_detail['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        if (empty($checkInfo)) {
            $this->helpJsonResult(500, '读取验车记录失败！');
        }
        $violate_remark = I('post.violate_remark');
        if (empty($violate_remark)) {
            $this->helpJsonResult(500, '请填写备注信息');
        }
        $params = array();
        // 获取表单信息
        $params['check_id'] = $check_id;
        $params['car_id'] = $order_detail['car_id']; // 车辆ID
        $params['order_id'] = $checkInfo['order_id']; // 车商验车ID
        $params['dealer_id'] = $checkInfo['dealer_id']; // 车商验车ID
        $params['emp_id'] = $this->emp_id;
        $params['remark'] = $violate_remark;
        $params['status'] = $this->dataStatus['violate']; // 处理结果(0:待处理, 1:跟踪中, 2:验车成功 3:验车失败 4: 违约)
        $params['dataStatus'] = $this->dataStatus;
        $params['check_time'] = date('Y-m-d H:i:s');
        // 业务处理
        try {
            $carCheck = new CarCheck();
            $res = $carCheck->save_car_dealer_check($params);
            if (!$res) {
                $this->helpJsonResult(500, '违约处理失败！');

            }
            $this->helpJsonResult(200, '更新成功');
        } catch (AuctionException $ex) {
            $this->helpJsonResult(500, $ex->getMessage());
        }
    }

    /**
     * 检验通过处理
     */
    public function doConsultPay()
    {
        if (!IS_POST) $this->helpJsonResult(500, "当前请求方式不合法！");
        // 验证拍单ID是否有效
        $orderID = I('post.order_id'); // 拍单ID
        $order = new AuOrder($orderID);
        $order_detail = $order->detail();
        if ($order_detail['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        $this->checkConsultOrderByID($orderID);
        $params = array();
        // 获取表单信息
        $params['check_id'] = I('post.check_id'); // 车商验车ID
        $params['order_id'] = $orderID;
        $params['emp_id'] = $this->emp_id;
        $params['emp_name'] = $this->user_info['real_name'];
        $params['dealer_id'] = I('post.dealer_id');
        $params['car_id'] = I('post.car_id');
        $params['status'] = $this->dataStatus['success']; // 处理结果(0:待处理, 1:跟踪中, 2:协商成功 3:协商失败)
        $params['remark'] = I('post.pay_remark', '', 'htmlspecialchars'); // 备注
        $params['check_time'] = I('post.check_time', ''); // 验车时间
        $params['dataStatus'] = $this->dataStatus;

        try {
            $CarCheck = new CarCheck();
            $res = $CarCheck->save_car_dealer_check($params);
            if (!$res) {
                $this->helpJsonResult(500, '验车处理失败！');
            }
            $this->helpJsonResult(200, '更新成功');
        } catch (AuctionException $ex) {
            $this->helpJsonResult(500, $ex->getMessage());
        }
    }

    public function doContinueTrace()
    {
        if (!IS_POST) $this->helpJsonResult(500, "当前请求方式不合法！");
        // 验证拍单ID是否有效
        $orderID = I('post.order_id'); // 拍单ID
        $order = new AuOrder($orderID);
        $order_detail = $order->detail();
        if ($order_detail['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        $this->checkConsultOrderByID($orderID);
        $checkId = I("post.check_id");
        if($checkId < 1){
            $this->helpJsonResult(400,"参数错误");
        }
        $next_trace_time = I("post.next_trace_time");
        if(empty($next_trace_time)){
            $this->helpJsonResult(400,"请选择下次跟踪时间");
        }

        $data = [];
        $data['status'] = $this->dataStatus['following'];
        $data['from'] = $this->dataStatus['following'];
        $data['order_id'] = $orderID;
        $data['dealer_id'] = I('post.dealer_id');
        $data['check_id'] = $checkId;
        $data['emp_id'] = $this->emp_id;
        $data['emp_name'] = $this->user_info['real_name'];
        $data['next_trace_time'] = $next_trace_time;
        $data['remark'] = I("post.trace_reason");

        try{
            $CarCheck = new CarCheck();
            $res = $CarCheck->save_car_dealer_check($data);
            if (!$res) {
                $this->helpJsonResult(500, '操作失败！');
            }
            $this->helpJsonResult(200, '更新成功');
        } catch (AuctionException $e){
            $this->helpJsonResult(500, $e->getMessage());
        }
    }

    private function record_log($order_id, $car_id, $action)
    {
        //记录员工操作日志
        $log = [
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => 0,
            'action' => $action
        ];
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);

        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
    }


    //违约
    public function violate()
    {
        $order_id = I("post.order_id/d", 0);
        if ($order_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $o = new AuOrder($order_id);
        $orderInfo = $o->detail();
        if ($orderInfo['is_lock'] == 1) {
            $this->helpJsonResult(400, "拍单已锁定");
        }
        $poInfo = $o->getPurchaseByOrderId();
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c->detail();
        $car_plate_number = C('PLATE_PREFIX')[$carInfo['plate_prefix']] . $carInfo['plate_suffix'];
        $data = [];
        $data['order_id'] = $order_id;
        $data['order_no'] = $orderInfo['order_no'];
        $data['po_id'] = $poInfo['id'];
        $data['sid'] = $poInfo['sid'];
        $data['po_no'] = $poInfo['purchase_order_nu'];
        $data['car_plate_number'] = $car_plate_number;
        $data['order_status'] = $orderInfo['status'];
        $data['source'] = 4;
        $data['originator'] = $this->emp_id;
        $res = ChangeOrder::CreateChangeOrder($data);
        if (!$res) {
            $this->helpJsonResult(400, '处理失败');
        }else{
            $now = date("Y-m-d H:i:s");
            $CarCheck = new CarCheck();
            $checkInfo = $CarCheck->get_car_check($order_id);
            $carCheckData = [
                'emp_id' => $this->emp_id,
                'updatetime' => $now
            ];
            //更新验车信息
            $CarCheck->updateByCheckId($checkInfo['check_id'],$carCheckData);
            //增加验车跟踪日志
            $checkLogData = [
                'emp_id' => $this->emp_id,
                'emp_name' => $this->user_info['real_name'],
                'action' => "车商违约",
                'create_at' => $now,
            ];
            $CarCheck->addCarDealerCheckLog($checkLogData);
            $this->record_log($order_id, $orderInfo['car_id'], "验车发起违约");
            $this->helpJsonResult(200, '处理成功');
        }
    }


    public function dispute(){
        $order_id = I("get.order_id/d", 0);
        if ($order_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $o = new AuOrder($order_id);
        $orderInfo = $o->detail();
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c->detail();
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($carInfo['brand_id'], 'brand');
        $series = $cm->get_model_by_id($carInfo['series_id'], 'series');
        $model = $cm->get_model_by_id($carInfo['model_id']);
        $car_model= $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $this->assign('order_id', $order_id);
        $this->assign('order_no', $orderInfo['order_no']);
        $this->assign('car_model', $car_model);
        $this->display();
    }

    //争议
    public function saveDispute(){
        $order_id = I("post.order_id/d", 0);
        if ($order_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $remark = I("post.remark");
        $dispute_reason = I("post.dispute_reason");
        $o = new AuOrder($order_id);
        $orderInfo = $o->detail();
        if ($orderInfo['is_lock'] == 1) {
            $this->helpJsonResult(400, "拍单已锁定");
        }
        $poInfo = $o->getPurchaseByOrderId();
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c->detail();
        $car_plate_number = C('PLATE_PREFIX')[$carInfo['plate_prefix']] . $carInfo['plate_suffix'];
        $data = [];
        $data['order_id'] = $order_id;
        $data['order_no'] = $orderInfo['order_no'];
        $data['po_id'] = $poInfo['id'];
        $data['po_no'] = $poInfo['purchase_order_nu'];
        $data['car_plate_number'] = $car_plate_number;
        $data['order_status'] = $orderInfo['status'];
        $data['od_id'] = $orderInfo['success_dealer_id'];
        $data['od_type'] = 1;
        $data['remark'] = $remark;
        $data['dispute_reason'] = $dispute_reason;
        $data['emp_id'] = $this->emp_id;
        $res = Dispute::DisputeAdd($data);
        if (!$res) {
            $this->helpJsonResult(400, '处理失败');
        }else{
            $now = date("Y-m-d H:i:s");
            $CarCheck = new CarCheck();
            $checkInfo = $CarCheck->get_car_check($order_id);
            $carCheckData = [
                'emp_id' => $this->emp_id,
                'updatetime' => $now
            ];
            //更新验车信息
            $CarCheck->updateByCheckId($checkInfo['check_id'],$carCheckData);
            //增加验车跟踪日志
            $checkLogData = [
                'emp_id' => $this->emp_id,
                'emp_name' => $this->user_info['real_name'],
                'action' => "车商争议",
                'create_at' => $now,
            ];
            $CarCheck->addCarDealerCheckLog($checkLogData);
            $this->record_log($order_id, $orderInfo['car_id'], "验车发起争议");
            $this->helpJsonResult(200, '处理成功');
        }
    }
}
